package top.went.service;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.PayRecordsDao;
import top.went.db.dao.PlanPayBackDao;
import top.went.db.dao.ReturnGoodsDao;
import top.went.db.mapper.PayRecordsMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.PaymentRecordsEntity;
import top.went.pojo.PlanPayBackEntity;
import top.went.pojo.PlanPayDetailEntity;
import top.went.pojo.ReturnGoodsEntity;
import top.went.vo.PageEntity;
import top.went.vo.PaymentRecordVO;
import top.went.vo.PlanPayBackVO;
import top.went.vo.PlanPayDetailVO;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;

@Service
@Transactional(value = "transactionManager", rollbackFor = ServiceException.class)
public class PayRecordsService {
    @Autowired
    private PayRecordsDao payRecordsDao;
    @Autowired
    private PayRecordsMapper payRecordsMapper;
    @Autowired
    private ReturnGoodsService returnGoodsService;
    @Autowired
    private ReturnGoodsDao returnGoodsDao;

    private static final Map<String, String> map = new HashMap<>();

    static {
        map.put("prMoney", "pr_money");
        map.put("prDate", "pr_date");
        map.put("prTerms", "pr_terms");
    }

    /**
     * 添加付款记录
     *
     * @param paymentRecordsEntity
     * @return
     * @throws ServiceException
     */
    public boolean pr_insert(PaymentRecordsEntity paymentRecordsEntity) throws ServiceException {
        try {
            if (paymentRecordsEntity.getTbCustomerByCusId() != null && paymentRecordsEntity.getTbCustomerByCusId().getCusId() != null) {
            } else
                paymentRecordsEntity.setTbCustomerByCusId(null);
            if (paymentRecordsEntity.getTbUserByUserId() != null && paymentRecordsEntity.getTbUserByUserId().getUserId() != null) {
            } else
                paymentRecordsEntity.setTbUserByUserId(null);
            if (paymentRecordsEntity.getTbPlanPayDetailByPpdId() != null && paymentRecordsEntity.getTbPlanPayDetailByPpdId().getPpdId() != null) {
            } else
                paymentRecordsEntity.setTbPlanPayDetailByPpdId(null);
            if (paymentRecordsEntity.getTbPurchaseByPurId() != null && paymentRecordsEntity.getTbPurchaseByPurId().getPurId() != null) {
            } else
                paymentRecordsEntity.setTbPurchaseByPurId(null);
            if (paymentRecordsEntity != null && paymentRecordsEntity.getPrMoney() != null) {
            } else paymentRecordsEntity.setPrMoney(null);
            if (paymentRecordsEntity.getTbReturnGoodsByRgId() != null && paymentRecordsEntity.getTbReturnGoodsByRgId().getRgId() != null) {
            } else paymentRecordsEntity.setTbReturnGoodsByRgId(null);
            if (paymentRecordsEntity.getPrType() == 1) {
                ReturnGoodsEntity returnGoodsEntity = returnGoodsService.load(paymentRecordsEntity.getTbReturnGoodsByRgId().getRgId());
                returnGoodsEntity.setToMoney(returnGoodsEntity.getToMoney() + paymentRecordsEntity.getPrMoney());
                System.out.println("==================================================="+returnGoodsEntity.getToMoney());
               returnGoodsDao.save(returnGoodsEntity);
            }
            return payRecordsDao.save(paymentRecordsEntity) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新建付款失败！");
        }
    }

    /**
     * 删除付款记录
     *
     * @param pr_id
     * @return
     * @throws ServiceException
     */
    public boolean pr_delete(int pr_id) throws ServiceException, NotFoundException {
        PaymentRecordsEntity paymentRecordsEntity = load(pr_id);
        if (paymentRecordsEntity == null)
            throw new NotFoundException("不存在该付款记录");
        try {
            paymentRecordsEntity.setMagicDelete(1l);
            return payRecordsDao.save(paymentRecordsEntity) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("删除付款记录失败");
        }
    }

    /**
     * 批量删除计划付款
     *
     * @param ids
     * @throws ServiceException
     */
    public boolean pr_logicDeleteAll(Long[] ids) throws ServiceException, NotFoundException {
        for (int i = 0; i < ids.length; i++) {
            pr_delete(ids[i].intValue());
        }
        return true;
    }

    /**
     * 修改付款记录
     *
     * @param paymentRecordsEntity
     * @return
     * @throws ServiceException
     */
    public boolean pr_update(PaymentRecordsEntity paymentRecordsEntity) throws ServiceException, NotFoundException {
        PaymentRecordsEntity paymentRecordsEntity1 = load(paymentRecordsEntity.getPrId());
        if (paymentRecordsEntity1 == null)
            throw new NotFoundException("付款记录不存在");
        paymentRecordsEntity1.setPrIsTicket(paymentRecordsEntity.getPrIsTicket());
        paymentRecordsEntity1.setPrTerms(paymentRecordsEntity.getPrTerms());
        paymentRecordsEntity1.setPrDate(paymentRecordsEntity.getPrDate());
        paymentRecordsEntity1.setPrMoney(paymentRecordsEntity.getPrMoney());
        try {
            return payRecordsDao.save(paymentRecordsEntity1) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("修改付款记录失败");
        }
    }

    /**
     * 查询所有付款记录
     *
     * @return
     */
    public PageEntity<PaymentRecordVO> pr_findAll(Integer pageSize, Integer pageNumber) throws ServiceException {
        try {
            List<PaymentRecordsEntity> rows = payRecordsDao.findAllByMagicDeleteOrderByPrIdDesc(0L, new PageRequest(pageNumber - 1, pageSize));
            int total = payRecordsDao.pr_findAllCount();
            return new PageEntity<PaymentRecordVO>((long) total, getPayRecordskVos(rows));
        } catch (Exception e) {
            throw new ServiceException("查询所有付款失败");
        }
    }

    /**
     * 根据付款日期查询付款
     *
     * @param pr_date
     * @return
     * @throws ServiceException
     */
    public PageEntity<PaymentRecordVO> pr_findByPpdDate(String pr_date, Integer pageSize, Integer pageNumber) throws ServiceException {
        try {
            String pr_date1 = "%" + pr_date + "%";
            System.out.println("date  " + pr_date1);
            Page<PaymentRecordsEntity> p = payRecordsDao.findAllByDate(pr_date1, new PageRequest(pageNumber - 1, pageSize));
            return new PageEntity<PaymentRecordVO>(p.getTotalElements(), getPayRecordskVos(p.getContent()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("根据付款日期查询付款记录失败");
        }
    }

    /**
     * 根据id查询计划付款实体
     *
     * @param prId
     * @return
     * @throws ServiceException
     * @throws NotFoundException
     */
    public PaymentRecordsEntity findOne(int prId) throws ServiceException, NotFoundException {
        PaymentRecordsEntity paymentRecordsEntity = payRecordsDao.findOne(prId);
        if (paymentRecordsEntity == null)
            throw new NotFoundException("付款不存在");
        return paymentRecordsEntity;
    }

    /**
     * 高级查询
     *
     * @param paymentRecordVO
     * @return
     * @throws ServiceException
     */
    public PageEntity<PaymentRecordsEntity> findAllByManyConditions(PaymentRecordVO paymentRecordVO) {
        if (paymentRecordVO == null)
            return new PageEntity<>(0l, null);
        String order = paymentRecordVO.getPage().getSort(map);
        if (order.length() <= 0)
            order = "pr_id desc";
        com.github.pagehelper.Page<PlanPayDetailEntity> page1 = PageHelper.startPage(paymentRecordVO.getPage().getPage(), paymentRecordVO.getPage().getSize(), order + " nulls last");
        payRecordsMapper.findByManyCondition(paymentRecordVO);
        return new PageEntity(page1.getTotal(), page1.getResult());
    }

    /**
     * 加载付款记录
     *
     * @param prId
     * @return
     * @throws ServiceException
     */
    public PaymentRecordsEntity load(Integer prId) throws ServiceException {
        try {
            return payRecordsDao.findAllByMagicDeleteAndPrId(0l, prId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("加载付款记录失败");
        }
    }

    /**
     * 加载计划付款
     *
     * @param prId
     * @return
     * @throws ServiceException
     */
    public PaymentRecordVO load1(Integer prId) throws ServiceException {
        try {
            return getPayRecordskVos1(payRecordsDao.findAllByMagicDeleteAndPrId(0l, prId));
        } catch (Exception e) {
            e.printStackTrace();
            ;
            throw new ServiceException("加载计划付款失败");
        }
    }

    private List<PaymentRecordVO> getPayRecordskVos(List<PaymentRecordsEntity> paymentRecordsEntities) {
        List<PaymentRecordVO> paymentRecordVOS = new ArrayList<>();
        for (PaymentRecordsEntity paymentRecordsEntity : paymentRecordsEntities) {
            paymentRecordVOS.add(new PaymentRecordVO(paymentRecordsEntity));
        }
        return paymentRecordVOS;
    }

    private PaymentRecordVO getPayRecordskVos1(PaymentRecordsEntity paymentRecordsEntity) {
        PaymentRecordVO paymentRecordVO = new PaymentRecordVO(paymentRecordsEntity);
        return paymentRecordVO;
    }
}
